//
//  MZmoreViewController.m
//  民族文化宫
//
//  Created by 何锦坤 on 14-8-2.
//  Copyright (c) 2014年 WANG CUNRUI. All rights reserved.
//

#import "MZmoreViewController.h"
#import "MZAppDelegate.h"
static NSString *ID = @"MyCell";
int count;
@interface MZmoreViewController ()<UITableViewDataSource,UITableViewDelegate>

//@property (weak,nonatomic) UITableView *messageView;
@property (strong, nonatomic) NSMutableArray *currentdata;
@property (nonatomic) NSInteger countp;
@property (strong,nonatomic) NSString *imagePath;


@end

@implementation MZmoreViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)cache
{
//    [super viewWillAppear:animated];
    
    //如果NSUserDefaults中没有ProductLastUpdate，则设置其初始值。
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"JieshaoLastUpdate"]) {
        [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"JieshaoLastUpdate"];
    }
    
    //获取全局变量
    MZAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    
    NSURL *productURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://210.30.0.167:6162/mzserver/ZhanpinCpinfo/findzhanpinCpinsbyID?id=%@&p=1",_MZID]];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:productURL];
    request.delegate = self;
    [request setDownloadCache:appDelegate.myCache];
    [request setCacheStoragePolicy:ASICachePermanentlyCacheStoragePolicy];
    
    //判断刷新时间间隔
    if ([MZTool IsNeedUpdate:@"JieshaoLastUpdate"]) {
        
        //只有在网络状态连通，且满足刷新时间间隔的情况下，request才不读缓存中的内容。
        //如果目前网络状态连通
        if ([MZTool IsEnable3G] == YES || [MZTool IsEnableWIFI] == YES) {
            [request setCachePolicy:ASIDoNotReadFromCacheCachePolicy];
            NSLog(@"从服务器读数据");
        }
        [request startAsynchronous];
        NSLog(@"主页下载中");
    }
    else
    {
        [request startAsynchronous];
    }

}


- (void)viewDidLoad
{
    [self cache];

    [super viewDidLoad];
    self.title = @"展览介绍";
    self.view = [[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
    self.view.backgroundColor = [UIColor colorWithRed:0.9373 green:0.9216 blue:0.9059 alpha:1.0];
//    self.edgesForExtendedLayout = UIRectEdgeNone;
    // 1. tableView
    CGRect frame = self.view.bounds;
    
    UITableView *moreView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height - 28) style:UITableViewStylePlain];
    // 1) 数据源
    [moreView setDataSource:self];
    // 2) 代理
    [moreView setDelegate:self];
    // 3) 设置表格高度
 //   [moreView setRowHeight:165];
    // 4) 设置分隔线
    [moreView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
//    UIBarButtonItem *rightBBI = [[UIBarButtonItem alloc] initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(bbiClick:)];
//    rightBBI.tag = 1;
//    self.navigationItem.rightBarButtonItem = rightBBI;
    
    [self.view addSubview:moreView];
    self.moreView = moreView;
    
    [self.moreView registerClass:[MZmoreTableViewCell class] forCellReuseIdentifier:ID];
    [self setupRefresh];
    [self Reshing];

    NSLog(@"%@",_MZID);
    // Do any additional setup after loading the view.
}

-(void)Reshing
{
    NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:@"http://210.30.0.167:6162/mzserver/ZhanpinCpinfo/findzhanpinCpinsbyID?id=%@&p=1",_MZID]];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:urls];
    //request.delegate = self;
    
    [request startSynchronous];
    NSLog(@"下载产品数据中");
    NSError *error = [request error];
    if (!error) {
        _currentdata = [[request responseData]JSONValue] ;
        [self.moreView reloadData];
    }
    else{
//        UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请检查网络连接" delegate:self cancelButtonTitle:@"确定"otherButtonTitles: nil];
//        [result show];
    }
    [self.moreView headerEndRefreshing];
    count = 2;
    _countp = 2;
}

- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.moreView addHeaderWithTarget:self action:@selector(headerRereshing)];
//    [self.moreView headerBeginRefreshing];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.moreView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark - 加载JSON
- (void)headerRereshing
{
    NSURL *urls = [NSURL URLWithString:[NSString stringWithFormat:@"http://210.30.0.167:6162/mzserver/ZhanpinCpinfo/findzhanpinCpinsbyID?id=%@&p=1",_MZID]];
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:urls];
    //request.delegate = self;
    [request startSynchronous];
    NSLog(@"下载产品数据中");
    NSError *error = [request error];
    if (!error) {
        _currentdata = [[request responseData]JSONValue] ;
        [self.moreView reloadData];
    }else{
        UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"加载数据失败" delegate:self cancelButtonTitle:@"确定"otherButtonTitles: nil];
        [result show];
    }
    // 给数据列表赋值
    // 2.1.5秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.moreView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.moreView headerEndRefreshing];
    });
//    if (_currentdata == nil) {
//        UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请检查网络连接" delegate:self cancelButtonTitle:@"是"otherButtonTitles: nil];
//        [result show];
//        
//    }
}



- (void)footerRereshing
{
    count = _countp;

    NSLog(@"countp = %ld",(long)_countp);
    if ((_currentdata != nil)) {
        [self startRefresh:count];
        NSLog(@"countp = %ld",(long)_countp);
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [self.moreView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.moreView footerEndRefreshing];
        });
    }
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.moreView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.moreView footerEndRefreshing];
    });
}



#pragma mark - 注册单元格

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 240;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_currentdata count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    MZmoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    NSDictionary *dic = _currentdata[indexPath.row];
    cell.textLabel.text = [dic objectForKey:@"cp_name"];
    cell.detailTextLabel.text = [dic objectForKey:@"cp_shuoming"];
    NSString *pic = [dic objectForKey:@"cp_wenwutu"];
    NSLog(@"pic=%@",pic);
    NSRange foundObj = [pic rangeOfString :@";" options:NSCaseInsensitiveSearch];
    if(foundObj.length>0)
    {
        NSRange range = [pic rangeOfString:@";"];
        NSString *b = [pic substringToIndex:range.location];
        NSLog(@"b = %@",b);
        NSString *imagePath = [NSString stringWithFormat:@"http://www.mzdigital.cn/%@", b];
        //        NSURL *imageUrl = [NSURL URLWithString:imagePath];
        NSLog(@"imagepath = %@",imagePath);
        _imagePath = imagePath;
    }else
    {
        NSString *imagePath = [NSString stringWithFormat:@"http://www.mzdigital.cn/%@", pic];
        //        NSURL *imageUrl = [NSURL URLWithString:imagePath];
        NSLog(@"%@",imagePath);
        _imagePath = imagePath;
    }
    //检测地址是否含有两张图片，有则取分号前一张
    [cell.imageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_imagePath]] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
//    NSLog(@"_imagepath = %@",_imagePath);
    
    
    return cell;
}


- (void)startRefresh:(int)count
{
    NSString *str = [NSString stringWithFormat:@"http://210.30.0.167:6162/mzserver/ZhanpinCpinfo/findzhanpinCpinsbyID?id=%@&p=%ld",_MZID,(long)count];
    
    NSURL *url = [NSURL URLWithString:str];
    NSLog(@"url2 = %@",url);
    // 2. 建立NSURLRequest
    ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
    //request.delegate = self;
    [request startSynchronous];
    //    _currentdata = [NSMutableArray array];
//    NSLog(@"current2 = %@",_currentdata);
    NSLog(@"下载产品数据中");
    NSError *error = [request error];
    if (!error) {
        NSData *data = [request responseData];
        NSLog(@"data2=%@",data.JSONValue );
        NSMutableArray *ARRAY = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSMutableArray *currentarray = [[NSMutableArray alloc]init];
        [currentarray addObjectsFromArray:_currentdata];
        [currentarray addObjectsFromArray:ARRAY];
        _currentdata = currentarray;
        if (![ARRAY  isEqual: @[]]) {
            NSLog(@"success");
            _countp = _countp + 1;
            count = count + 1;
            
            NSLog(@"count11 = %ld",(long)count);
            
        }
        NSLog(@"count = %ld",(long)count);
        _countp = count;
//        NSLog(@"array = %@",ARRAY);
//        NSLog(@"current2.1 = %@",_currentdata);
        // 刷新表格
        [self.moreView reloadData];
    }
    else{
        UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"加载数据失败" delegate:self cancelButtonTitle:@"确定"otherButtonTitles: nil];
        [result show];
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    _moredetailcontroller = [[MZmoredetailViewController alloc] init];
    NSDictionary *dic = _currentdata[indexPath.row];
    _moredetailcontroller.leibie = [dic objectForKey:@"cp_leibie"];
    _moredetailcontroller.minzu = [dic objectForKey:@"cp_minzu"];
    _moredetailcontroller.pic = [dic objectForKey:@"cp_wenwutu"];
    _moredetailcontroller.time = [dic objectForKey:@"cp_shidai"];
    _moredetailcontroller.content_c = [dic objectForKey:@"cp_shuoming"];
    _moredetailcontroller.content_e = [dic objectForKey:@"TITLE"];
    _moredetailcontroller.chicun = [dic objectForKey:@"cp_chicun"];
    _moredetailcontroller.diqu = [dic objectForKey:@"cp_diqu"];
    _moredetailcontroller.zhidi = [dic objectForKey:@"cp_zhidi"];;
    _moredetailcontroller.name = [dic objectForKey:@"cp_name"];
    
    [self.navigationController pushViewController:_moredetailcontroller animated:YES];
    
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    //    NSData *data = [request responseData];
    _currentdata = [[request responseData] JSONValue];
    
    [self.moreView reloadData];
    
    //判断数据来源并决定是否刷新数据更新时间
    if ([request didUseCachedResponse] == NO) {
        [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"JieshaoLastUpdate"];
        NSLog(@"数据来自服务器,展览下载成功");
    }
    else
    {
        NSLog(@"数据来自缓存,展览下载成功");
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    UIAlertView *result = [[UIAlertView alloc] initWithTitle:@"提示" message:@"数据加载失败" delegate:self cancelButtonTitle:@"确定"otherButtonTitles: nil];
    [result show];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
